﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Ast.Core.Forms;

namespace Ast
{
    public partial class ListViewForm<T> : Form
    {
        private readonly ListViewFormDataSource<T> _dataSource;

        public ListViewForm(ListViewFormDataSource<T> dataSource)
        {
            _dataSource = dataSource;

            InitializeComponent();
        }

        private void ListViewForm_Load(object sender, EventArgs e)
        {
            // set form properties
            if (!string.IsNullOrEmpty(_dataSource.Title))
            {
                this.Text = _dataSource.Title;
            }

            listView.BeginUpdate();

            // init columns
            foreach (var column in _dataSource.Columns)
            {
                listView.Columns.Add(new ColumnHeader {Name = column.Name, Text = column.Name, Tag = column.Tag});
            }

            // insert data
            var items = new List<ListViewItem>(_dataSource.Data.Count);
            items.AddRange(_dataSource.Data.Select(rowData => new ListViewItem(_dataSource.Columns.Select((column, index) => _dataSource.DataGeters[index](rowData, column)).ToArray())));
            listView.Items.AddRange(items.ToArray());

            // sorting
            listView.ApplyColumnSorter();
            listView.Sort();
            listView.AutoResizeColumns();

            listView.EndUpdate();
        }
    }

    public class ListViewColumn
    {
        public string Name { get; set; }
        public string Tag { get; set; }
    }

    public class ListViewFormDataSource<T>
    {
        public string Title { get; set; }
        public IList<ListViewColumn> Columns { get; set; }
        public IList<T> Data { get; set; }
        public IList<Func<T, ListViewColumn, string>> DataGeters { get; set; }
    }
}